from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from configparser import ConfigParser
import time


def load_cookies(config):
    cookies = []

    def add_cookie(name, value, domain, path="/", secure=False, httpOnly=False):
        cookies.append({
            "name": name,
            "value": value,
            "domain": domain,
            "path": path,
            "secure": secure,
            "httpOnly": httpOnly
        })

    # 主登录 Cookie
    add_cookie(
        name="access_token",
        value=config.get("cookies", "access_token"),
        domain=config.get("cookies", "access_token_domain"),
        path=config.get("cookies", "access_token_path"),
        secure=config.getboolean("cookies", "access_token_secure"),
        httpOnly=config.getboolean("cookies", "access_token_httponly")
    )

    add_cookie(
        name="HMACCOUNT",
        value=config.get("cookies", "hmaccount"),
        domain=config.get("cookies", "hmaccount_domain"),
        path=config.get("cookies", "hmaccount_path")
    )

    # 百度统计 Cookie
    add_cookie(
        name=config.get("cookies", "hm_lvt_name"),
        value=config.get("cookies", "hm_lvt"),
        domain=config.get("cookies", "hm_lvt_domain"),
        path=config.get("cookies", "hm_lvt_path")
    )

    add_cookie(
        name=config.get("cookies", "hm_lpvt_name"),
        value=config.get("cookies", "hm_lpvt"),
        domain=config.get("cookies", "hm_lpvt_domain"),
        path=config.get("cookies", "hm_lpvt_path")
    )

    return cookies


def load_config():
    config = ConfigParser()
    config.read('config.ini', encoding='utf-8')

    return {
        "user_agent": config.get('settings', 'user_agent'),
        "target_url": config.get('settings', 'target_url'),
        "referer_url": config.get('settings', 'referer_url'),
        "cookies": load_cookies(config)
    }


def init_browser(user_agent):
    chrome_options = Options()
    chrome_options.add_argument(f"user-agent={user_agent}")
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")
    return webdriver.Chrome(options=chrome_options)


def main():
    config = load_config()
    driver = init_browser(config["user_agent"])

    try:
        # 初始化上下文，确保域名已加载
        driver.get(config["referer_url"])
        time.sleep(2)

        # 注入所有 Cookie
        for cookie in config["cookies"]:
            driver.add_cookie(cookie)

        # 跳转到目标页面
        driver.get(config["target_url"])
        print("✅ 操作完成 - 浏览器保持打开中")
        print(f"🌐 当前URL: {driver.current_url}")
        input("按回车键退出程序...")

    except Exception as e:
        print(f"❌ 发生错误: {e}")
        driver.save_screenshot("error.png")
    finally:
        driver.quit()


if __name__ == "__main__":
    main()
